package com.bwie.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.poi.StringUtils;
import com.bwie.pojo.Menu;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.LoginVo;
import com.bwie.vo.PageInfoVo;
import com.bwie.vo.ReginInfoVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.bouncycastle.operator.bc.BcDigestProvider;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.User;
import com.bwie.mapper.UserMapper;
import com.bwie.service.UserService;

import javax.servlet.http.HttpServletRequest;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    @Autowired
    UserMapper userMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    HttpServletRequest request;

    @Override
    public R sendCode(String mobile) {
        String code = RandomUtil.randomNumbers(4);
        System.out.println("验证码"+code);
        String key1="code:"+mobile;

        boolean mobile1 = Validator.isMobile(mobile);
        if(!mobile1){
            return R.ERROR(500,"手机号错误");
        }

        stringRedisTemplate.opsForValue().set(key1,code,5, TimeUnit.MINUTES);
        MobileMessageUtil.sendMobileMessage(mobile,code);
        return R.OK();
    }

    @Override
    public R login(LoginVo loginVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userMapper.selectOne(wrapper.lambda().eq(User::getUserMobile, loginVo.getMobile()));
        if(user==null){
            return R.ERROR(500,"账号不存在");
        }



        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(loginVo.getPass(), user.getUserPass());
        if(!matches){
            return R.ERROR(500,"密码不正确");
        }

//        String key1="code:"+reginInfoVo.getMobile();
//        String redisCode = stringRedisTemplate.opsForValue().get(key1);
//        if(redisCode==null){
//            return R.ERROR(500,"验证码已过期");
//        }
//        if(!redisCode.equals(reginInfoVo.getCode())){
//            return R.ERROR(500,"验证码不正确");
//        }

        String token = Jwts.builder().signWith(SignatureAlgorithm.HS256, "bwie").claim("userId", user.getUserId()).claim("userName",user.getUserName()).compact();
        String key="token:"+user.getUserId();
        stringRedisTemplate.opsForValue().set(key,token,30,TimeUnit.MINUTES);

        //获取当前用户的角色列表
        List<String> roleList=userMapper.getRoleList(user.getUserId());
        user.setRoleList(roleList);


        user.setToken(token);
        return R.OK(user);
    }

    @Override
    public R userRegister(ReginInfoVo reginInfoVo) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        User user = userMapper.selectOne(wrapper.lambda().eq(User::getUserMobile, reginInfoVo.getMobile()));
        if(user!=null){
            return R.ERROR(500,"用户已存在");
        }

        String key1="code:"+reginInfoVo.getMobile();
        String redisCode = stringRedisTemplate.opsForValue().get(key1);
        if(redisCode==null){
            return R.ERROR(500,"验证码已过期");
        }
        if(!redisCode.equals(reginInfoVo.getCode())){
            return R.ERROR(500,"验证码不正确");
        }

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String hashPass = encoder.encode(reginInfoVo.getPass());
        User user1 = new User();
        user1.setUserPass(hashPass);
        user1.setUserMobile(reginInfoVo.getMobile());
        user1.setUserName("匿名用户");
        user1.setCreateTime(new Date());
        user1.setCreateBy("系统");
        userMapper.insert(user1);
        return R.OK();
    }

    @Override
    public R menuList() {
        String token = request.getHeader("token");
        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("userId", Integer.class);
        List<Menu> menuList=userMapper.selesctgetMenuListByUserId(userId);
        List<Tree<String>> treeList = TreeUtil.build(menuList, "0", (tree, node) -> {
            node.setId(tree.getMenuId().toString());
            node.setName(tree.getMenuName());
            node.setParentId("" + tree.getMenuPid());
            node.putExtra("path", tree.getMenuPath());
        });
        return R.OK(treeList);
    }

    @Override
    public R userList(PageInfoVo pageInfoVo) {
        Page<User> page = new Page<>(pageInfoVo.getPageNum(), pageInfoVo.getPageSize());
        Page<User> userPage=userMapper.getShopUserList(page,pageInfoVo);
        return R.OK(userPage);
    }


}
